package cn.jjxx.modules.xmgl.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.MapBeanUtil;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

import org.framework.superutil.thirdparty.excel.ExcelDataFormatter;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import cn.jjxx.modules.common.bean.UploadExcel;
import cn.jjxx.modules.sys.entity.Staff;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.xmgl.entity.Coordinates;
import cn.jjxx.modules.xmgl.entity.EqProjectCoordinates;
import cn.jjxx.modules.xmgl.entity.EqProjectCoordinatesExt;
import cn.jjxx.modules.xmgl.entity.XmglFiliale;
import cn.jjxx.modules.xmgl.service.IEqProjectCoordinatesService;
import cn.jjxx.modules.map.service.ICommonMapService;
import cn.jjxx.modules.sbfb.entity.EqProjectInfo;
import cn.jjxx.modules.sbfb.service.IEqProjectInfoService;

/**
 * @Title: 项目经纬度坐标
 * @Description: 项目经纬度坐标
 * @author yw
 * @date 2022-02-18 14:07:20
 * @version V1.0
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/xmgl/eqprojectcoordinates")
@RequiresPathPermission("xmgl:eqprojectcoordinates")
public class EqProjectCoordinatesController extends BaseBeanController<EqProjectCoordinates> {

	@Autowired
	protected IEqProjectCoordinatesService eqProjectCoordinatesService;
	@Autowired
	protected ICommonMapService commonMapService;
	@Autowired
	protected IEqProjectInfoService eqProjectInfoService;

	/**
	 * @Description: 根据获取项目经纬度坐标的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	public EqProjectCoordinates get(String id) {
		if (!ObjectUtils.isNullOrEmpty(id)) {
			return eqProjectCoordinatesService.selectById(id);
		} else {
			return newModel();
		}
	}

	/**
	 * @Description: 跳转至项目经纬度坐标的列表界面 .<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	//@RequiresMethodPermissions("list")
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        String projectId = request.getParameter("projectId");
        if(!StringUtils.isEmpty(projectId)) {
    		model.addAttribute("projectId", projectId);
        }
        String projectName = request.getParameter("projectName");
        if(!StringUtils.isEmpty(projectName)) {
    		model.addAttribute("projectName", projectName);
        }
		return display("list");
	}

	/**
	 * @Description: 项目经纬度坐标的列表界面获取列表结果 .<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
	private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		EntityWrapper<EqProjectCoordinates> entityWrapper = new EntityWrapper<EqProjectCoordinates>(entityClass);
		propertyPreFilterable.addQueryProperty("id");
		entityWrapper.eq("1", "1");
		entityWrapper.orderBy("project_id,type,sort");
        String size = request.getParameter("page.size");
        
        String projectId = request.getParameter("projectId");
        if(!StringUtils.isEmpty(projectId)) {
        	projectId = projectId.replace("~","=").replace("!","/").replace(".", "+");
    		entityWrapper.eq("project_id", projectId);
        }
        
        if(StringUtils.isEmpty(size)) {
            List<EqProjectCoordinates> list = eqProjectCoordinatesService.selectList(entityWrapper);
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("results", list);
            map.put("page", 1);
            map.put("rows", list.size());
            map.put("total", list.size());
            map.put("totalPages", 1);
            String content = JSON.toJSONString(map);
	        StringUtils.printJson(response, content);
        }else {
    		// 预处理
    		QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
    		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
    		PageJson<EqProjectCoordinates> pagejson = new PageJson<EqProjectCoordinates>(
    				eqProjectCoordinatesService.list(queryable, entityWrapper));
    		String content = JSON.toJSONString(pagejson, filter);
    		StringUtils.printJson(response, content);
        }
	}
	

	@RequestMapping(value = "listCoordinates", method = { RequestMethod.GET, RequestMethod.POST })
	private void listCoordinates(HttpServletRequest request, HttpServletResponse response) throws IOException {
		EntityWrapper<EqProjectCoordinates> entityWrapper = new EntityWrapper<EqProjectCoordinates>(entityClass);
		entityWrapper.eq("1", "1");
		entityWrapper.orderBy("project_id,type,sort");
		EntityWrapper<EqProjectInfo> wrapper = new EntityWrapper<EqProjectInfo>();
		List<EqProjectCoordinatesExt> returnList =null;
		AjaxJson aj = new AjaxJson();
		String projectId = request.getParameter("projectId");
		if(!StringUtils.isEmpty(projectId)) {
			entityWrapper.eq("project_id", projectId);
		}else {
			String companyId = request.getParameter("companyId");
			List<EqProjectInfo> listEqProjectInfos = new ArrayList<>();
			if(!StringUtils.isEmpty(companyId)) {
				wrapper.eq("org_id", companyId);
				listEqProjectInfos = eqProjectInfoService.selectList(wrapper);
				List<Object> listIds = MapBeanUtil.ListDoSelect(listEqProjectInfos, "id");
				entityWrapper.in("project_id", listIds);
				if(null == listIds || listIds.size() <=0) {
					returnList = new ArrayList<EqProjectCoordinatesExt>();
					aj.setData(returnList);
					String content = JSON.toJSONString(aj);
					StringUtils.printJson(response, content);
					return;
				}
			}
		}
		String type = request.getParameter("type");
		if(!StringUtils.isEmpty(type)) {
			entityWrapper.eq("type", type);
		}
		List<EqProjectCoordinates> list = eqProjectCoordinatesService.selectList(entityWrapper);
		 returnList = changeToList(list);
		if(null==returnList || returnList.size()<=0) {
			returnList = new ArrayList<EqProjectCoordinatesExt>();
		}
		aj.setData(returnList);
		String content = JSON.toJSONString(aj);
		StringUtils.printJson(response, content);
	}

	private List<EqProjectCoordinatesExt> changeToList(List<EqProjectCoordinates> list) {
		List<EqProjectCoordinatesExt> ret = new ArrayList<EqProjectCoordinatesExt>();
		for (EqProjectCoordinates c : list) {
			EqProjectCoordinatesExt e =  existsData(ret,c);
			Coordinates co = new Coordinates();
			co.setLantitude(c.getLantitude());
			co.setLongitude(c.getLongitude());
			if(null!=e) {
				e.getCoordinates().add(co);
			}else {
				e = new EqProjectCoordinatesExt();
				e.setProjectId(c.getProjectId());
				e.setProjectName(c.getProjectName());
				e.setType(c.getType());
				e.getCoordinates().add(co);
				ret.add(e);
			}
		}
		return ret;
	}

	private EqProjectCoordinatesExt existsData(List<EqProjectCoordinatesExt> list, EqProjectCoordinates c) {
		
		for (EqProjectCoordinatesExt e : list) {
			if(e.getProjectId().equals(c.getProjectId()) && e.getType().equals(c.getType())) {
				return e;
			}
		}
		return null;
	}

	/**
	 * @Description: 跳转至项目经纬度坐标的添加界面 .<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
		if (!model.containsAttribute("data")) {
			EqProjectCoordinates epc =newModel();
			String projectId = request.getParameter("projectId");
			String projectName = request.getParameter("projectName");
			epc.setProjectId(projectId);
			epc.setProjectName(projectName);
			model.addAttribute("data", epc);
		}
		return display("edit");
	}

	/**
	 * @Description: 新增项目经纬度坐标的数据 .<br>
	 * @param eqProjectCoordinates 项目经纬度坐标实体类.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson create(Model model, @Valid @ModelAttribute("data") EqProjectCoordinates eqProjectCoordinates,
			BindingResult result, HttpServletRequest request, HttpServletResponse response) {
		return doSave(eqProjectCoordinates, request, response, result);
	}

	/**
	 * @Description: 跳转至项目经纬度坐标的更新界面 .<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "{id}/update", method = RequestMethod.GET)
	public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		id = id.replace("~","=").replace("!","/").replace(".", "+");
		EqProjectCoordinates eqProjectCoordinates = get(id);
		eqProjectCoordinates.setpId(eqProjectCoordinates.getProjectId());
		model.addAttribute("data", eqProjectCoordinates);
		return display("edit");
	}

	/**
	 * @Description: 修改项目经纬度坐标的数据 .<br>
	 * @param eqProjectCoordinates 项目经纬度坐标实体类.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "{id}/update", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson update(Model model, @Valid @ModelAttribute("data") EqProjectCoordinates eqProjectCoordinates,
			BindingResult result, HttpServletRequest request, HttpServletResponse response) {
		return doSave(eqProjectCoordinates, request, response, result);
	}

	/**
	 * @Description: 执行保存项目经纬度坐标的数据操作 .<br>
	 * @param eqProjectCoordinates 项目经纬度坐标实体类.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson doSave(EqProjectCoordinates eqProjectCoordinates, HttpServletRequest request,
			HttpServletResponse response, BindingResult result) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("保存成功");
		if (hasError(eqProjectCoordinates, result)) {
			// 错误提示
			String errorMsg = errorMsg(result);
			if (!StringUtils.isEmpty(errorMsg)) {
				ajaxJson.fail(errorMsg);
			} else {
				ajaxJson.fail("保存失败");
			}
			return ajaxJson;
		}
		try {
			if (StringUtils.isEmpty(eqProjectCoordinates.getId())) {
				eqProjectCoordinatesService.insert(eqProjectCoordinates);
			} else {
				eqProjectCoordinatesService.insertOrUpdate(eqProjectCoordinates);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
		}
		return ajaxJson;
	}

	/**
	 * @Description: 单条删除项目经纬度坐标 .<br>
	 * @param id 单据Id.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson delete(@PathVariable("id") String id) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("删除成功");
		TableName table = EqProjectCoordinates.class.getAnnotation(TableName.class);
		String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
		try {
			List<String> ids = Arrays.asList(id.split(","));
			// 得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if (StringUtils.isNotEmpty(quoteMsg)) {
				ajaxJson.setMsg("删除失败," + quoteMsg);
				return ajaxJson;
			}
			eqProjectCoordinatesService.deleteById(id);
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.fail("删除失败");
		}
		return ajaxJson;
	}

	/**
	 * @Description: 执行保存项目经纬度坐标的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("批量删除成功");
		TableName table = EqProjectCoordinates.class.getAnnotation(TableName.class);
		String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
		try {
			List<String> idList = java.util.Arrays.asList(ids);
			// 得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if (StringUtils.isNotEmpty(quoteMsg)) {
				ajaxJson.setMsg("批量删除失败," + quoteMsg);
				return ajaxJson;
			}
			eqProjectCoordinatesService.deleteBatchIds(idList);
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.fail("批量删除失败");
		}
		return ajaxJson;
	}

	/**
	 * @Description: 跳转至项目经纬度坐标的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
			HttpServletResponse response) {
		EqProjectCoordinates eqProjectCoordinates = get(id);
		eqProjectCoordinates.setpId(eqProjectCoordinates.getProjectId());
		model.addAttribute("data", eqProjectCoordinates);
		return display("edit");
	}

	/**
	 * @Description: 验证项目经纬度坐标功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20.<br>
	 */
	@RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
		ValidJson validJson = new ValidJson();
		Boolean valid = Boolean.FALSE;
		try {
			EntityWrapper<EqProjectCoordinates> entityWrapper = new EntityWrapper<EqProjectCoordinates>(entityClass);
			valid = eqProjectCoordinatesService.doValid(duplicateValid, entityWrapper);
			if (valid) {
				validJson.setStatus("y");
				validJson.setInfo("验证通过!");
			} else {
				validJson.setStatus("n");
				if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
					validJson.setInfo(duplicateValid.getErrorMsg());
				} else {
					validJson.setInfo("当前信息重复!");
				}
			}
		} catch (Exception e) {
			validJson.setStatus("n");
			validJson.setInfo("验证异常，请检查字段是否正确!");
		}
		return validJson;
	}

	/**
	 * @Description: 得到可以被审核的单据 .<br>
	 * @param bills  单据Id集合.<br>
	 * @param status 可操作状态.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20 .<br>
	 */
	private List<String> getAllowOptBills(List<String> bills, String status) {
		EntityWrapper<EqProjectCoordinates> wrapper = new EntityWrapper<EqProjectCoordinates>();
		wrapper.in("id", bills);
		wrapper.eq("status", status);
		List<EqProjectCoordinates> list = eqProjectCoordinatesService.selectList(wrapper);
		bills = new ArrayList<String>();
		for (EqProjectCoordinates bean : list) {
			bills.add(bean.getId());
		}
		return bills;
	}

	/**
	 * @Description: 设置批量更新参数 .<br>
	 * @param bills     可以操作的Id集合.<br>
	 * @param newStatus 被修改的状态设置值.<br>
	 * @author yw .<br>
	 * @date 2022-02-18 14:07:20 .<br>
	 */
	private List<EqProjectCoordinates> setBacthUpdate(List<String> bills, String newStatus) {
		List<EqProjectCoordinates> list = new ArrayList<EqProjectCoordinates>();
		User user = UserUtils.getUser();
		if (bills.size() > 0) {
			list = eqProjectCoordinatesService.selectBatchIds(bills);
			for (EqProjectCoordinates bean : list) {
				bean.setStatus(Integer.valueOf(newStatus));
				if (newStatus.equals(String.valueOf(BillConfig.SAVE))
						|| newStatus.equals(String.valueOf(BillConfig.SUBMIT))) {
				}
			}
		}
		return list;
	}

	@RequestMapping(value = "expexcel", method = RequestMethod.GET)
	public void expexcel(Model model, UploadExcel excel, HttpServletRequest request, HttpServletResponse response) {

		ExcelUtils.setIsExportTemplate(true);
		ExcelUtils.setFirstTitle("项目经纬度模板");
		ExcelUtils.setSecTitle("导出人："+UserUtils.getUser().getRealname());
		ExcelUtils.downloadXlsx(response, null, EqProjectCoordinates.class, null, "项目经纬度模板");
	}


	@RequestMapping(value = "impExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson impExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		response.setContentType("text/plain");
		j.setMsg("导入成功");
		String projectId=request.getParameter("nodeId");
		if (StringUtils.isEmpty(projectId)) {
			j.setRet(AjaxJson.RET_FAIL);
			j.setMsg("请先选择项目,再导入!!!");
			return j;
		}
		//id.replace("=","~").replace("/","!").replace('+', '.');
		projectId = projectId.replace("~","=").replace("!","/").replace(".", "+");
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> ite = multiRequest.getFileNames();
			while (ite.hasNext()) {
				try {
					MultipartFile file = multiRequest.getFile(ite.next());
					CommonsMultipartFile cFile = (CommonsMultipartFile) file;
					DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
					InputStream inputStream = fileItem.getInputStream();
					List<EqProjectCoordinates> list =  new ExcelUtils<EqProjectCoordinates>(
															new EqProjectCoordinates())
							.readFromFile(null, inputStream);
					// 判断excel上传数据是否符合要求
					j = checkAndSet(list,projectId);
					if (j.getRet() !=0 ) {
						return j;
					}
					eqProjectCoordinatesService.insertOrUpdateBatch(list);
				} catch (Exception e) {
					e.printStackTrace();
					j.setRet(AjaxJson.RET_FAIL);
					j.setMsg("导入失败");
				}
			}
		}
		return j;
	}

	private AjaxJson checkAndSet(List<EqProjectCoordinates> list, String projectId) {
		AjaxJson json=new AjaxJson(); 
		json.setMsg("导入成功");
		if(list.size()<=0) {
			json.fail("导入数据不能为空!!!");
			return json;
		}
		
		for (EqProjectCoordinates e : list) {
			e.setProjectId(projectId);
			if(StringUtils.isEmpty(e.getLongitude()) || StringUtils.isEmpty(e.getLantitude())) {
				json.fail("经纬度不能为空!!!");
				return json;
			}
		}
		
		return json;
	}
}
